package com.gateway.api.util;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IPUtil  extends ClassicConverter {


    private static Logger logger = LoggerFactory.getLogger(IPUtil.class);

    private static String hostIp;

    public static String getIp() {
        if (hostIp == null) {
            InetAddress address = null;
            try {
                address = InetAddress.getLocalHost();
            }
            catch (UnknownHostException e) {
                logger.error("get ip error ...");
            }
            hostIp = address.getHostAddress();
        }
        return hostIp;
    }

    public static String getIpFromRequest(HttpServletRequest request) {{
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    }

    @Override
    public String convert(ILoggingEvent iLoggingEvent) {
        return IPUtil.getIp();
    }
}
